package com.soundShape.mediators.newCustomer
{
	
	import com.soundShape.events.SoundShapeEvent;
	import com.soundShape.mediators.AbstractViewMediator;
	import com.soundShape.model.ApplicationModel;
	import com.soundShape.popUps.AddSpecialDate;
	import com.soundShape.popUps.ReferralPopUp;
	import com.soundShape.views.login.Login;
	import com.soundShape.views.newCustomer.NewCustomer;
	import com.soundShape.vo.CustomerVO;
	import com.soundShape.vo.ReferralVO;
	import com.soundShape.vo.SpecialDateVO;
	
	import flash.events.Event;
	import flash.events.FocusEvent;
	import flash.events.MouseEvent;
	import flash.events.TextEvent;
	import flash.text.TextExtent;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.core.UIComponent;
	import mx.effects.Move;
	import mx.effects.Rotate;
	import mx.events.CloseEvent;
	import mx.events.ItemClickEvent;
	import mx.managers.PopUpManager;
	
	import nz.co.codec.flexorm.criteria.Criteria;
	
	import spark.components.BorderContainer;
	import spark.components.RadioButton;
	import spark.components.RadioButtonGroup;
	import spark.components.TextArea;
	import spark.components.TextInput;
	
	
	
	
	public class NewCustomerMediator extends AbstractViewMediator
	{
		
			
				private var lenTxtAraCustomerAddress:int;
				private var lenTxtInCustomerEmail:int;
				private var lenTxtInCustomerName:int;
				private var lenTxtInCustomerPhone:int;
				
				private var isLockNewCustomer:Boolean;
				
				private var collReferrals:ArrayCollection;
				
				public function NewCustomerMediator()
				{
					super(NewCustomer);
				}
				
				/**
				 * Since the AbstractViewMediator sets the view via Autowiring in Swiz,
				 * we need to create a local getter to access the underlying, expected view
				 * class type.
				 */
				public function get view():NewCustomer
				{
					return this._view as NewCustomer;
				}
				
				/**
				 * The <code>init()</code> method is fired off automatically by the 
				 * AbstractViewMediator when the creation complete event fires for the
				 * corresponding ViewMediator's view. This allows us to listen for events
				 * and set data bindings on the view with the confidence that our view
				 * and all of it's child views have been created and live on the stage.
				 */
				override protected function init():void
				{
					super.init();
					
					this.setViews();
					
				}
				
				private function setViews():void
				{
					this.collReferrals = new ArrayCollection();
				}
				
				override protected function setViewDataBindings():void
				{
					super.setViewDataBindings();
				}	
				
				override protected function setViewListeners():void
				{
					super.setViewListeners();
					
					//this.view.btnMenu.addEventListener(MouseEvent.CLICK, handleBtnMenu);
					
					this.view.btnNewCustomer.addEventListener(MouseEvent.CLICK, handleBtnNewCustomer);
					
					this.view.txtInCustomerName.addEventListener(MouseEvent.CLICK, handleTxtInCustomerNameClick);
					
					this.view.txtAraCustomerAddress.addEventListener(TextEvent.TEXT_INPUT, handleTextInput);
					this.view.txtInCustomerEmail.addEventListener(TextEvent.TEXT_INPUT, handleTextInput);
					this.view.txtInCustomerName.addEventListener(TextEvent.TEXT_INPUT, handleTextInput);
					this.view.txtInCustomerPhone.addEventListener(TextEvent.TEXT_INPUT, handleTextInput);
					
					this.view.btnSubmitSpecialDate.addEventListener(MouseEvent.CLICK, handleSubmitSpecialDate);
					
					this.view.radGrpReferal.addEventListener(ItemClickEvent.ITEM_CLICK, handleRadGrpReferal);
					
					this.view.imgPlus.addEventListener(MouseEvent.CLICK, handleImgPlusClick);
					
					//for tutorial only
					this.view.txtInCustomerName.addEventListener(FocusEvent.FOCUS_OUT, handleFocusOut);
				}
				
				/**
				 * for tutorial
				 */
				protected function handleFocusOut(event:FocusEvent):void
				{
					if(this.view.txtInCustomerName.text == "Oscar Cote")
					{
						this.view.txtAraCustomerAddress.text = "230 Commercial Street\nBoston, Massachusetts\n02129";
						this.view.txtInCustomerEmail.text = "oscar@sound-shapes.com";
						this.view.txtInCustomerPhone.text = "617-367-1900";
					}
						this.view.btnNewCustomer.enabled = true;
					
				}
				
				protected function handleImgPlusClick(event:MouseEvent):void
				{
					//get customers for referrals combobox
					var criteria:Criteria = applicationModel.entityManager.createCriteria(CustomerVO);
					var customers:ArrayCollection = this.applicationModel.entityManager.fetchCriteria(criteria);
					
					var referralPopUp:ReferralPopUp = new ReferralPopUp();
					referralPopUp.applicationModel = this.applicationModel;
					referralPopUp.collCustomers = customers;
					referralPopUp.callback = callbackReferral;
					referralPopUp.viewState = "create";
					PopUpManager.addPopUp(referralPopUp,this.view,true);
					PopUpManager.centerPopUp(referralPopUp);
				}
				
				protected function handleRadGrpReferal(event:ItemClickEvent):void
				{
					var lbl:Object = RadioButtonGroup(event.currentTarget).selectedValue;

					if(lbl == "referral")
					{
						
						//get customers for referrals combobox
						var criteria:Criteria = applicationModel.entityManager.createCriteria(CustomerVO);
						var customers:ArrayCollection = this.applicationModel.entityManager.fetchCriteria(criteria);
						
						var referralPopUp:ReferralPopUp = new ReferralPopUp();
						referralPopUp.applicationModel = this.applicationModel;
						referralPopUp.collCustomers = customers;
						referralPopUp.callback = callbackReferral;
						referralPopUp.viewState = "create";
						PopUpManager.addPopUp(referralPopUp,this.view,true);
						PopUpManager.centerPopUp(referralPopUp);
					}
					else
					{
						this.view.imgPlus.visible = false;
						collReferrals.removeAll(); // if referrals were added, then the grp changes, obviously get rid of the referrals
					}
						
				}	
				
				public function callbackReferral(referralVO:ReferralVO):void
				{
					if(referralVO != null)
					{
						collReferrals.addItem(referralVO);
						this.view.imgPlus.visible = true;
					}
					else
					{
						this.view.radGrpReferal.selectedValue = null;
					}
					
					if(this.view.btnNewCustomer.enabled)
						doGreenArrowNewCustomer();
				}
				
				private function doGreenArrowNewCustomer():void
				{
					this.view.greenArrowNewCustomer.doGreenArrow();					
				}				
				
				
				
				/**
				 * *******************************************************************************
				 * Handlers
				 * *******************************************************************************
				 */
				private function handleBtnMenu(mouseEvent:MouseEvent):void
				{
					resetCustomerForm();
					this.dispatcher.dispatchEvent(new SoundShapeEvent(SoundShapeEvent.SWITCH_TO_MENU_VIEW));
				}
				
				
				private function handleBtnNewCustomer(mouseEvent:MouseEvent):void
				{
					 var customerVO:CustomerVO = new CustomerVO();
					 customerVO.address = this.view.txtAraCustomerAddress.text;
					 customerVO.email = this.view.txtInCustomerEmail.text;
					 customerVO.name = this.view.txtInCustomerName.text;
					 customerVO.phone = this.view.txtInCustomerPhone.text;
					 customerVO.reference = this.view.radGrpReferal.selectedValue as String;
					 customerVO.employeeID = this.applicationModel.employeeVO.id;
					 
					 if(!isDuplicateCustomer(customerVO))
					 {
						var customerID:int = this.applicationModel.entityManager.save(customerVO);
						 
						Alert.show("Customer creation successful","Success",Alert.OK, this.view, handleAlertClose, null, Alert.OK);
						 
						//save the referralVO's
						for each(var referralVO:ReferralVO in this.collReferrals)
						{
							referralVO.customerID = customerID;
							referralVO.customerName = customerVO.name;
						}
						
						//and save it - again
						this.applicationModel.entityManager.save(referralVO);
						 
						//lock this form so that it cannot be re-submitted
						isLockNewCustomer = true;
						this.dispatcher.dispatchEvent(new SoundShapeEvent(SoundShapeEvent.GET_CUSTOMERS));
						 
						//place this VO in the model
						this.applicationModel.customerVO = customerVO;
						 
						// employee can now add 'Special Dates'
						this.view.pnSpecialDate.enabled = true;
						
					 }
					 else
					 {
						 // error: 
						 Alert.show("Attempted duplication of record", "Alert");
					 }
					
					 // do not reset form - instead give employee ability to add 'Special Dates'
					 this.view.btnNewCustomer.enabled = false;
				}
				
				private function handleAlertClose(eventObj:CloseEvent):void
				{
					this.view.greenArrow.doGreenArrow();
				}
				
				private function isDuplicateCustomer(customerVO:CustomerVO):Boolean
				{
					var isDupe:Boolean = false;
					
					var criteria:Criteria = applicationModel.entityManager.createCriteria(CustomerVO);
					
					var customers:ArrayCollection = applicationModel.entityManager.fetchCriteria(criteria);
					
					for each (var customer:CustomerVO in customers)
					{
						if((customer.name == customerVO.name)&&(customer.address == customerVO.address)&&(customer.email == customerVO.email))
						{
							isDupe = true;
							break;
						}
					}
					
				return isDupe;
				}
				
				/**
				 * this function is fired only if the employee moves away from this view
				 */
				private function resetCustomerForm():void
				{
					// reset the new customer form
					this.view.txtAraCustomerAddress.text = "";
					this.view.txtInCustomerEmail.text = "";
					this.view.txtInCustomerName.text = "";
					this.view.txtInCustomerPhone.text = "";
					this.view.radGrpReferal.selection = null;
					lenTxtAraCustomerAddress = 0;
					lenTxtInCustomerEmail = 0;
					lenTxtInCustomerName = 0;
					lenTxtInCustomerPhone = 0;
					this.view.btnNewCustomer.enabled = false;
					this.view.pnSpecialDate.enabled = false;
					this.view.btnSubmitSpecialDate.enabled = false;
					this.isLockNewCustomer = false;
					
					//reset special dates
					resetSpecialDate();
					
					this.view.imgPlus.visible = false;
				}
				
				private function handleTxtInCustomerNameClick(mouseEvent:MouseEvent):void
				{
					this.view.lblNewCustomerInfo.text = "";
				}
				
				
				
				private function handleTextInput(textEvent:TextEvent):void
				{
					//employee cannot edit this customer in this view once submitted
					if(this.isLockNewCustomer)
						return;
					
					var id:String;
					
					if(textEvent.currentTarget is TextInput)
						id = TextInput(textEvent.currentTarget).id;
					else
						id = TextArea(textEvent.currentTarget).id;
					
					switch(id)
					{
						case "txtAraCustomerAddress":
							lenTxtAraCustomerAddress++;
							break;
						
						case "txtInCustomerEmail":
							lenTxtInCustomerEmail++;
							break;
						
						case "txtInCustomerName":
							lenTxtInCustomerName++;
							break;
						
						case "txtInCustomerPhone":
							lenTxtInCustomerPhone++;
							break;
					}
					
					if(
						(lenTxtAraCustomerAddress > 5) &&
						(lenTxtInCustomerEmail > 5) &&
						(lenTxtInCustomerName > 5) &&
						(lenTxtInCustomerPhone > 5)
					  ){
						this.view.btnNewCustomer.enabled = true;
					}
				}
				
				
				protected function handleSubmitSpecialDate(event:MouseEvent):void
				{
					var initDates:int = getTotalSpecialDates(); // number of entries before the save
					
					var specialDateVO:SpecialDateVO = new SpecialDateVO();
					specialDateVO.customerID = this.applicationModel.customerVO.id;
					specialDateVO.employeeID = this.applicationModel.employeeVO.id;
					specialDateVO.specialDate = this.view.dtfldSpecialDate.selectedDate;
					specialDateVO.specialDateType = this.view.txtInDateType.text;
					specialDateVO.specialDateNotes = this.view.txtAreaNotes.text;
					
					this.applicationModel.entityManager.save(specialDateVO);
					
					var finalDates:int = getTotalSpecialDates(); // entries after the save
					
					// check to make sure the save was successful
					if(finalDates == (initDates+1))
						Alert.show("Special Date was successfully created.\nYou may add another, or go to 'Main Menu'","Success");
					else
						Alert.show("Special Date was NOT created","Error");
					
					resetSpecialDate();
					
					//add the special date to the datagrid
					var criteria:Criteria = applicationModel.entityManager.createCriteria(SpecialDateVO);
					criteria.addEqualsCondition("customerID",this.applicationModel.customerVO.id);
					
					var specialDates:ArrayCollection = this.applicationModel.entityManager.fetchCriteria(criteria);
					this.view.dgSpecialDates.dataProvider = specialDates;
					
				}
				
				private function resetSpecialDate():void
				{
					this.view.dtfldSpecialDate.text = "";
					this.view.txtInDateType.text = "";
					this.view.txtAreaNotes.text = "";
					this.view.btnSubmitSpecialDate.enabled = false;
					
				}
				
				private function getTotalSpecialDates():int
				{
					var criteria:Criteria = applicationModel.entityManager.createCriteria(SpecialDateVO);
					var specialDates:ArrayCollection = this.applicationModel.entityManager.fetchCriteria(criteria);
					return specialDates.length;
				}
					
				
				/**
				 * *******************************************************************************
				 * Swiz EventHanders
				 * *******************************************************************************
				 */
				[EventHandler(event="SoundShapeEvent.RESET_VIEW_NEW_CUSTOMER")]
				public function doResetViewNewCustomer(soundShapeEvent:SoundShapeEvent):void
				{
					if(this.view == null)
						return;
					
					this.view.txtAraCustomerAddress.text = "";
					this.view.txtAreaNotes.text = "";
					this.view.txtInCustomerEmail.text = "";
					this.view.txtInCustomerName.text = "";
					this.view.txtInCustomerPhone.text = "";
					this.view.radGrpReferal.selectedValue = null;
				}
			
		}
		
	}
